//
//  RoamingViewController.m
//  JiuLe
//
//  Created by 黄鑫 on 16/9/18.
//  Copyright © 2016年 Fine. All rights reserved.
//

#import "RoamingViewController.h"
#import "VRGCalendarView.h"
#import "UWDatePickerView.h"
#import "MallRequestManager.h"
#import "MoneyPayViewController.h"
#import "TransactionDetailsViewController.h"
@interface RoamingViewController ()<VRGCalendarViewDelegate>
@property (weak, nonatomic) IBOutlet UIButton *btnStart;
@property (weak, nonatomic) IBOutlet UIButton *btnEnd;
@property (weak, nonatomic) IBOutlet UIButton *btnInput;
@property (weak, nonatomic) IBOutlet UILabel *labPrice;
@property (weak, nonatomic) IBOutlet UILabel *labStart;
@property (weak, nonatomic) IBOutlet UILabel *labEnd;
@property (weak, nonatomic) IBOutlet UIButton *btnJiFei;
@property (nonatomic, strong) VRGCalendarView *pickerView;
@property (nonatomic, strong) UIView *maskView;
@property (nonatomic,strong)NSString *fee;
@property (nonatomic,strong)NSMutableDictionary *dataDic;
@property(nonatomic,strong)MoneyPayViewController *MoneyPayVC;
@property(nonatomic,strong)UIButton *btnView;
@property (strong, nonatomic) UIToolbar *toolbar;
@property (strong, nonatomic) UILabel *labTip;
@end

@implementation RoamingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"漫游开通";
    [self showNavgationWithLeftItemWithTitle:@"返回"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.labStart.text = @"";
    self.labEnd.text = @"";
    self.labPrice.text = @"";
    self.btnInput.enabled = NO;
    self.btnInput.backgroundColor = [UIColor orangeColor];
    self.btnInput.layer.cornerRadius = 21.0;
    self.btnInput.layer.masksToBounds = YES;
     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(removeMoneyPayVC) name:@"removeMoneyPayVCFromType2" object:nil];
     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(pushToHistoryVC) name:@"FromRoamingVCPushHistoryVC" object:nil];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    //[self initToolbar];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    //[_toolbar removeFromSuperview];
    
}

- (void)pushToHistoryVC
{
    [_MoneyPayVC.view removeFromSuperview];
    TransactionDetailsViewController *transactionDetails = [[UIStoryboard storyboardWithName:@"PersonalViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"TransactionDetailsViewController"];
    transactionDetails.orderId = [NSString stringWithFormat:@"%@",[[self.dataDic objectForKey:@"orderid"] stringValue]];
    transactionDetails.flag = @"2";
    [self.navigationController pushViewController:transactionDetails animated:YES];
}
- (void)removeMoneyPayVC
{
    [_MoneyPayVC.view removeFromSuperview];
    [self.btnView removeFromSuperview];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 1) {
        return SCREEN_HEIGHT - 250 - 64;
    }else{
        return 0.1;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section == 0) {
        return nil;
    }else{
        float height = SCREEN_HEIGHT - 250 - 64;
        UIView *viewBotton = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, height)];
        self.labTip = [[UILabel alloc] initWithFrame:CGRectMake(0,height - 44,SCREEN_WIDTH, 44)];
        self.labTip.text = @"开通漫游费需要至少提前三天申请，若遇节假日往后顺延";
        self.labTip.numberOfLines = 0;
        self.labTip.font = [UIFont systemFontOfSize:14.0f];
        self.labTip.textAlignment = NSTextAlignmentCenter;
        [viewBotton addSubview:self.labTip];
        return viewBotton;
    }
}

- (IBAction)startAction:(UIButton *)sender {
    sender.selected =YES;
    self.btnEnd.selected = NO;
    [self setupDateView:DateTypeOfStart];
}

- (IBAction)endAction:(UIButton *)sender {
   
   
    if ([_labStart.text isEqualToString:@""]) {
        _labEnd.text = @"";
        [SVProgressHUD showErrorWithStatus:@"请选择开通时间"];
        return;
    }else
    {
        sender.selected =YES;
        self.btnStart.selected = NO;
        [self setupDateView:DateTypeOfStart];
       
        
    }
}

- (IBAction)jiFeiAction:(id)sender
{
    if ((![self.labStart.text isEqualToString:@""]&&![self.labEnd.text isEqualToString:@""])) {
        int compare =  [self compareDate:self.labStart.text withDate:self.labEnd.text];
        if (compare ==-1) {
            self.btnInput.enabled = NO;
            [SVProgressHUD showErrorWithStatus:@"结束日期不能小于开始日期"];
            self.labPrice.text = @"";
        }else
        {
            self.btnInput.enabled = YES;
            //获取漫游费用
            NSMutableDictionary *params = [NSMutableDictionary new];
            [params setObject:self.labStart.text forKey:@"start_date"];
            [params setObject:self.labEnd.text forKey:@"end_date"];
            [SVProgressHUD showWithStatus:@"加载中..."];
            [MallRequestManager post:@"Charge/wander" RequestParams:params FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                if (connectionError) {
                   
                    [self performSelectorOnMainThread:@selector(showNetworkError) withObject:nil waitUntilDone:YES];
                    return ;
                }else
                {
                    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                    
                    if ([dic.allKeys containsObject:@"result"]) {
                        
                        if (!([[dic objectForKey:@"status"]intValue]==200)) {
                            [SVProgressHUD dismiss];
                            [SVProgressHUD showErrorWithStatus:@"日期选择错误"];
                            self.fee = @"";
                        }else
                        {
                            NSDictionary *result = [dic objectForKey:@"result"];
                            self.fee = [result objectForKey:@"fee"];
                            [SVProgressHUD dismiss];
                        }
                    }
                }
                [self performSelectorOnMainThread:@selector(reloadUI) withObject:nil waitUntilDone:YES];
                
            }];

            
        }
    }else
    {
        self.btnInput.enabled = NO;
        [SVProgressHUD showErrorWithStatus:@"请选择开通和结束时间"];
    }
}
- (void)showNetworkError
{
    self.labPrice.text = @"";
}
- (IBAction)inputAction:(id)sender {
   
    [self uploadDataOfOrder];
    
}
//生成订单
- (void)uploadDataOfOrder
{
    NSMutableDictionary *params = [NSMutableDictionary new];
    NSString *userID = [[NSUserDefaults standardUserDefaults]objectForKey:@"userID"];
    [params setObject:userID forKey:@"user_id"];
    NSString *token = [[NSUserDefaults standardUserDefaults]objectForKey:@"token"];
    [params setObject:token forKey:@"token"];
    [params setObject:@"2" forKey:@"type"];//1：服务费类型 2：漫游类型
    [params setObject:self.labStart.text forKey:@"start_date"];
    [params setObject:self.labEnd.text forKey:@"end_date"];
    [SVProgressHUD showWithStatus:@"加载中..."];
    [MallRequestManager post:@"Charge/orderadd" RequestParams:params FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        if (connectionError) {
            [SVProgressHUD showErrorWithStatus:@"数据请求失败"];
        }else
        {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            if ([dic.allKeys containsObject:@"message"]) {
                NSString *message = [dic objectForKey:@"message"];
                [SVProgressHUD showSuccessWithStatus:message];
            }
            self.dataDic = [NSMutableDictionary new];
            if ([dic.allKeys containsObject:@"result"]) {
                self.dataDic = [dic objectForKey:@"result"];
                [self performSelectorOnMainThread:@selector(showPayVC) withObject:nil waitUntilDone:YES];
            }
        }
        [SVProgressHUD dismiss];
    }];

}
- (void)showPayVC
{
    
    //添加蒙层 弹出付款页面
    self.tableView.scrollEnabled =NO; //设置tableview 不能滚动
    self.btnView = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, self.tableView.frame.size.height)];
    self.btnView.backgroundColor = [UIColor grayColor];
    [self.btnView addTarget:self action:@selector(btnViewClicked) forControlEvents:UIControlEventTouchUpInside];
    self.btnView.alpha = 0.6f;
    [self.tableView addSubview:self.btnView];
    _MoneyPayVC = [[UIStoryboard storyboardWithName:@"MallViewController" bundle:nil]instantiateViewControllerWithIdentifier:@"MoneyPay"];
    [self addChildViewController:_MoneyPayVC];
    _MoneyPayVC.view.frame = CGRectMake(0, self.tableView.contentSize.height-(self.tableView.contentSize.height-self.tableView.contentOffset.y-self.view.frame.size.height)-300, self.tableView.frame.size.width,300);
    _MoneyPayVC.view.alpha = 1.0;
    [self.tableView addSubview:_MoneyPayVC.view];
    _MoneyPayVC.flag = @"2";//2表示从服务费付款页跳转订单详情
    NSMutableDictionary *dic = [NSMutableDictionary new];
    dic = self.dataDic ;
    [dic setObject:@"2" forKey:@"type"];
    NSNotification *notification =[NSNotification notificationWithName:@"SubmitOrdersIsClicked" object:nil userInfo:self.dataDic];
    [[NSNotificationCenter defaultCenter] postNotification:notification];
}
- (void)btnViewClicked
{
    self.tableView.scrollEnabled =YES;
    [self.btnView removeFromSuperview];
    [_MoneyPayVC.view removeFromSuperview];
}
#pragma mark - VRGCalendarView Delegate
-(void)calendarView:(VRGCalendarView *)calendarView
    switchedToMonth:(int)month
       targetHeight:(float)targetHeight
           animated:(BOOL)animated {
}

- (void)calendarView:(VRGCalendarView *)calendarView dateSelected:(NSDate *)date {
    [self hiddenPickerView];
    NSTimeInterval  oneDay = 24*60*60*1;  //1天的长度
    NSInteger dis = 4; //前后的天数
    NSDate *currentDate = [NSDate date];
    NSDate *mDate = [currentDate initWithTimeIntervalSinceNow:oneDay*dis];
    NSDateFormatter  *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString  *queryDate = [dateFormatter stringFromDate:date];
    NSString *minDate = [dateFormatter stringFromDate:mDate];
    int result;
    result = [self compareDate:minDate withDate:queryDate];
    if (result==-1) {
        [SVProgressHUD showErrorWithStatus:@"开始日期必须大于当前日期3天"];
        if (self.btnStart.selected ==YES) {
            self.labStart.text = @"";
        }
        if (self.btnEnd.selected == YES) {
            self.labEnd.text = @"";
        }
        self.btnInput.enabled = NO;
        return;
    }
    if (self.btnStart.selected ==YES) {
        self.labStart.text = queryDate;
    }
    if (self.btnEnd.selected == YES) {
        self.labEnd.text = queryDate;
    }
    if (![self.labStart.text isEqualToString:@""]&&![self.labEnd.text isEqualToString:@""]) {
        int result = [self compareDate:self.labStart.text withDate:self.labEnd.text];
        if (result == -1) {
            self.labStart.text = self.labEnd.text;
        }
    }
}
-(int)compareDate:(NSString*)date01 withDate:(NSString*)date02{
    int ci;
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd"];
    NSDate *dt1 = [[NSDate alloc] init];
    NSDate *dt2 = [[NSDate alloc] init];
    dt1 = [df dateFromString:date01];
    dt2 = [df dateFromString:date02];
    NSComparisonResult result = [dt1 compare:dt2];
    switch (result)
    {
            //date02比date01大
        case NSOrderedAscending: ci=1; break;
            //date02比date01小
        case NSOrderedDescending: ci=-1; break;
            //date02=date01
        case NSOrderedSame: ci=0; break;
        default: NSLog(@"erorr dates %@, %@", dt2, dt1); break;
    }
    return ci;
}
- (void)reloadUI
{
    
    self.labPrice.text = [NSString stringWithFormat:@"￥%@",self.fee];
}
- (void)setupDateView:(DateType)type {
    if (_pickerView == nil) {
        _maskView = [[UIView alloc] initWithFrame:self.view.bounds];
        [_maskView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                action:@selector(hiddenPickerView)]];
        _maskView.backgroundColor = [[UIColor grayColor] colorWithAlphaComponent:0.4];
        [self.view addSubview:_maskView];
        _maskView.tag = 0x22;
        _pickerView = [[VRGCalendarView alloc] initWithFrame:CGRectMake(CGRectGetWidth(self.view.bounds)/2 - kVRGCalendarViewWidth/2, CGRectGetHeight(self.view.frame)/2 - 271 / 2, kVRGCalendarViewWidth, 0)];
        _pickerView.delegate = self;
        [self.view addSubview:_pickerView];
        
    } else {
        [self hiddenPickerView];
        [self.view addSubview:_pickerView];
    }
}

- (void)hiddenPickerView {
    _maskView.hidden = _pickerView.hidden= !_pickerView.hidden;
}

- (void)initToolbar{
    self.labTip = [[UILabel alloc] initWithFrame:CGRectMake(0,0,SCREEN_WIDTH, 44)];
    self.labTip.text = @"开通漫游费需要至少提前三天申请，若遇节假日往后顺延";
    self.labTip.numberOfLines = 0;
    self.labTip.font = [UIFont systemFontOfSize:14.0f];
    self.labTip.textAlignment = NSTextAlignmentCenter;
    self.labTip.backgroundColor = RGB(239, 244, 244);
    UIBarButtonItem *btn1=[[UIBarButtonItem alloc] initWithCustomView:self.labTip];
    _toolbar=[[UIToolbar alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 40,SCREEN_WIDTH, 40)];
    NSArray *arr1=[[NSArray alloc]initWithObjects:btn1, nil];
    _toolbar.items = arr1;
    _toolbar.clipsToBounds = YES;//去黑色线
    [_toolbar setShadowImage:[UIImage new] forToolbarPosition:UIBarPositionTop];
    [[UIApplication sharedApplication].keyWindow addSubview:_toolbar];
}

-(void)dealloc{
    NSLog(@"removeMoneyPayVCFromType2通知被移除,pushHistoryVC通知被移除");
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"removeMoneyPayVCFromType2" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"pushHistoryVC" object:nil];
}
@end
